<?php
/* 兑换 */
namespace Api\Controller;
use Think\Controller;
use Think\Log;
class PBeginnerWelfareController extends Controller {
 	
 	private $user = array();
	public function __construct()
	{
		//解决跨域
		echoHeader();
		$phone = I('post.phone', '', 'trim');
		// $phone = '13660392546';
        $this->user = session('p_user');
		if(!$this->user or $this->user['phone'] != $phone){
			$this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请先登录'));
		}
        $this->user = M("PUser")->where(array("phone"=>$phone, "is_deleted"=>0))->find();
		if (!$this->user) {
			$this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请先登录'));
		}
        $this->user['score']=user_score_sum($this->user['id']);
	}

	public function index()
	{
		$map['start_time'] = array('lt', time());
		$map['end_time'] = array('gt', time());
	    $map['is_deleted']=0;
		$pageSize = 100;
		$pageIndex = I('post.page', 1, 'intval');
		$total = M("PBeginnerWelfare")->where($map)->count();
		$order = I('post.order', 'asc', 'trim');
		$order = strtolower($order);
		if(!in_array($order, array('desc', 'asc'))){
			$order = 'asc';
		}
		$page = $this->pagination($total, $pageSize ,$pageIndex);

		if($total){
			$list = M("PBeginnerWelfare")->field('id,name,link,url')->where($map)
					->limit($page['offset'], $page['limit'])->order('add_time '.$order)->select();
		}else{
			$list = array();
		}
		$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>array('list'=>$list,'page'=>$page)));

	}

	private function pagination($total, $pageSize, $pageIndex)
	{
	    $page = array();
	    $totalPages = ceil($total / $pageSize);
	    $pageIndex <= 0 and $pageIndex = 1;
	    $offset = ($pageIndex - 1) * $pageSize;

	    $page['limit'] = $pageSize;
	    $page['offset'] = $offset;
	    $page['total'] = (int)$total;//总条目数
	    $page['total_pages'] = (int)$totalPages;//总页数
	    $page['current_page'] = $pageIndex;//当前页数
	    $page['has_nextpage'] = $totalPages > $pageIndex;//是否还有下一页
	    return $page;
	}
	
}